package com.ruoyi.common.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.vo.WeChatVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;


@Slf4j
@Component
public class WeChatUtil {

    private String wechatAppId = "wxfbb89868ec9e6a96";

    private String wechatAppSecret = "09ec09d42d8353836a1dbffb7d5d13ca";


    public WeChatVO getWeChatInfo(String weChatCode) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+wechatAppId+"&secret="+wechatAppSecret+"&js_code="+weChatCode+"&grant_type=authorization_code";
        log.info("url={}",url);

        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(url, String.class);
        log.info("response={}",response);
        WeChatVO weChatDTO = JSON.parseObject(response, WeChatVO.class);
        return weChatDTO;
    }

    /**
     * 获取accessToken
     * @return
     */
    public String getAccessToken(){
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+wechatAppId+"&secret="+wechatAppSecret;
        String result = HttpRequest.get(url).execute().body();
        log.info("Access Token 接口返回数据={}",result);
        Map<String, Object> map = JSON.parseObject(result, Map.class);
        String access_token = map.get("access_token").toString();
        log.info("获取到的access_token===={}",access_token);
        return access_token;
    }

    /**
     * 获取用户手机号
     * @param code
     * @return
     */
    public String getUserPhoneNumber(String code){
        String access_token = this.getAccessToken();
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+access_token;
        JSONObject jsonObject = JSONUtil.createObj();
        jsonObject.putOpt("code",code);
        String result = HttpRequest.post(url).body(jsonObject.toString()).execute().body();
        log.info("获取用户手机号接口返回数据={}",result);
        Map<String, Object> map = JSON.parseObject(result, Map.class);
        Map<String, Object> mapPhone = JSON.parseObject(map.get("phone_info").toString(), Map.class);
        return mapPhone.get("purePhoneNumber").toString();
    }

    public String getQrCode(Long roomId) {
        String access_token = this.getAccessToken();
        String url = "https://api.weixin.qq.com/wxa/getwxacode?access_token="+access_token;
        JSONObject jsonObject = JSONUtil.createObj();
        jsonObject.putOpt("path","pages/index/index?roomId="+roomId);
        String result = HttpRequest.post(url).body(jsonObject.toString()).execute().body();
        log.info("获取小程序二维码接口={}",result);
        return result;
    }

}
